import 'dart:io';

import 'package:simulator/utils/options.dart';
import 'package:simulator/utils/utils.dart';

class RomAndRam {
  static final RomAndRam _instance = RomAndRam._internal();
  RomAndRam._internal();

  static RomAndRam getInstance() => _instance;

  late final List<int> _rom;
  late final List<int> _ram;

  late final int _romSize;

  void loadFirmware(CMD cmd) {
    _romSize = cmd.romSize;

    try {
      if (!cmd.isHex) {
        var f = File(cmd.path).readAsBytesSync();
        _rom = List.from(f);
        if (f.length > _romSize) {
          throw 'firmware over size,please inc rom size';
        }
      } else {}
    } catch (e) {
      Utils.getInstance().abort(e.toString());
    }
    _ram = List.generate(cmd.ramSize, (index) => 0);
  }

  void reset() {}
  get romSize => _romSize;
  get ramSize => _ram.length;
  int getCode(int index) => index >= _rom.length ? 0xff : _rom[index];

  List<int> getData(int start, int end) =>
      _rom.getRange(start, start + end).toList();

  int getRamData(int index) => _ram[index];
  void setRamData(int index, int value) => _ram[index] = (value & 0xff);
}
